package org.wj.config.temperature;

import lombok.extern.java.Log;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * 定义一个适当的数据结构保存键和值，另外还需要提供中间键的排序顺序；
 * 如果需要持久存储定制数据类型，则必须实现Writable接口；
 * 如果要比较定制数据类型，还需要实现WritableComparable接口
 */
@Log
public class DateTemperaturePair implements Writable, WritableComparable<DateTemperaturePair> {
    // 数据格式 2019,01,01,1019031605
    // 数据结果 2019-01 1019031605
    private Text yearMonth = new Text();
    private Text day = new Text();
    private LongWritable temperature = new LongWritable();

    public Text getYearMonth() {
        return yearMonth;
    }

    public void setYearMonth(Text yearMonth) {
        this.yearMonth = yearMonth;
    }

    public Text getDay() {
        return day;
    }

    public void setDay(Text day) {
        this.day = day;
    }

    public LongWritable getTemperature() {
        return temperature;
    }

    public void setTemperature(LongWritable temperature) {
        this.temperature = temperature;
    }

    @Override
    public int compareTo(DateTemperaturePair pair) {
        int compareValue = this.yearMonth.compareTo(pair.getYearMonth());
        if (compareValue == 0) {
            compareValue = temperature.compareTo(pair.getTemperature());
        }
        // 倒序排序
        return -compareValue;

    }

    @Override
    public void write(DataOutput dataOutput) throws IOException {
        yearMonth.write(dataOutput);
        day.write(dataOutput);
        temperature.write(dataOutput);
    }

    @Override
    public void readFields(DataInput dataInput) throws IOException {
//        2012,01,01,5
        yearMonth.readFields(dataInput);
        day.readFields(dataInput);
        temperature.readFields(dataInput);
    }
}
